package cn.jichangxiu.ucenter.filter;

import cn.jichangxiu.common.ucenter.model.AuthToken;
import cn.jichangxiu.common.utils.CookieUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//@WebFilter(filterName="AuthFilter",urlPatterns="/*")
public class AuthFilter implements Filter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //从头取出jwt令牌
    public String getJwtFromHeader(HttpServletRequest request) {
        //取出头信息
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            return null;
        }
        if (!authorization.startsWith("Bearer ")) {
            return null;
        }
        //取到jwt令牌
        String jwt = authorization.substring(7);
        return jwt;
    }

    //从cookie取出token
    //查询身份令牌
    public String getTokenFromCookie(HttpServletRequest request) {
        Map<String, String> cookieMap = CookieUtils.readCookie(request, "uid");
        String accessToken = cookieMap.get("uid");
        if (StringUtils.isEmpty(accessToken)) {
            return null;
        }
        return accessToken;
    }

    //查询令牌的有效期
    public long getExpire(String accessToken) {
        //key
        String key = "accessToken:" + accessToken;
        Long expire = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
        return expire;
    }

    public AuthToken getAuthToken(String accessToken) {
        String key = "accessToken:" + accessToken;
        String jsonToken = stringRedisTemplate.opsForValue().get(key);
        AuthToken authToken = JSON.parseObject(jsonToken, AuthToken.class);
        return authToken;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse hres = (HttpServletResponse) response;
        HttpServletRequest hreq = (HttpServletRequest) request;
        String accessToken = getTokenFromCookie(hreq);
        if (!StringUtils.isEmpty(accessToken)) {
            long time = getExpire(accessToken);
            if (time > 0){
                AuthToken authToken = getAuthToken(accessToken);
                if (authToken != null){
                    String jwtToken = authToken.getJwtToken();
                    System.out.println(jwtToken);
                }
            }
        }
        chain.doFilter(hreq, hres);
    }

    @Override
    public void destroy() {
    }
}
